<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">角色管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!home_console">首页</a>
          <a><cite>角色管理</cite></a>
        </span>
    </div>
    <div class="layui-card-body">
        <div class="layui-form toolbar">
            搜索：<input id="role-edit-search" class="layui-input search-input" type="text" placeholder="输入角色名或备注"/>&emsp;
            <button id="role-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
        </div>

        <!-- 数据表格 -->
        <table class="layui-table" id="role-table" lay-filter="role-table"></table>
    </div>
</div>

<!-- 表单弹窗 -->
<script type="text/html" id="role-model">
    <form id="role-form" lay-filter="role-form" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">角色名<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input name="roleName" placeholder="请输入角色名" type="text" class="layui-input" maxlength="20"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="comments" placeholder="请输入内容" class="layui-textarea" maxlength="200"></textarea>
            </div>
        </div>
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn layui-btn-primary close" type="button">取消</button>
            <button class="layui-btn" lay-filter="role-form-submit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 表头操作列 -->
<script type="text/html" id="role-table-bar">
    <div class="layui-inline" lay-event="add" lay-tips="新增"><i class="layui-icon layui-icon-add-1"></i></div>
    <div class="layui-inline" lay-event="edit" lay-tips="修改"><i class="layui-icon layui-icon-edit"></i></div>
    <div class="layui-inline" lay-event="del" lay-tips="删除"><i class="layui-icon layui-icon-delete"></i></div>
    <div class="layui-inline" lay-event="auth" lay-tips="权限管理"><i class="layui-icon layui-icon-auz"></i></div>
</script>

<script>
    layui.use(['form', 'table', 'util', 'admin'], function () {
        const $ = layui.jquery;
        const form = layui.form;
        const table = layui.table;
        const layer = layui.layer;

        let formUrl;  // 表单提交的action

        //渲染表格
        table.render({
            elem: '#role-table',
            url: basePath + 'system/role/list',
            toolbar: '#role-table-bar',
            defaultToolbar: ['filter'],
            page: true,
            cols: [
                [
                    {type: 'radio', fixed: 'left'},
                    {field: 'roleName', sort: true, title: '角色名'},
                    {field: 'comments', sort: true, title: '备注'},
                    {field: 'createDate', sort: true, title: '创建时间'},
                ]
            ]
        });

        // 表单提交事件
        form.on('submit(role-form-submit)', function (data) {
            layer.load(2);
            $.post(formUrl, data.field, function (data) {
                layer.closeAll('loading');
                if (data.success) {
                    layer.closeAll('page');
                    layer.msg(data.msg, {icon: 1});
                    table.reload('role-table');
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            });
            return false;
        });

        // 工具条点击事件
        table.on('toolbar(role-table)', function (obj) {
            const checkStatus = table.checkStatus(obj.config.id); //获取选中行状态
            const data = checkStatus.data;  //获取选中行数据
            switch (obj.event) {
                case 'add':
                    addOrEdit();
                    break;
                case 'edit':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                        return;
                    }
                    addOrEdit(data[0]);
                    break;
                case 'del':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                        return;
                    }
                    del(data[0].id);
                    break;
                case 'auth':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                        return;
                    }
                    auth(data[0].id);
                    break;
            }
        });

        // 新增|修改
        const addOrEdit = function (data) {
            layer.open({
                type: 1,
                title: data ? '修改角色' : '添加角色',
                area: '450px',
                offset: '120px',
                content: $('#role-model').html(),
                success: function () {
                    $('#role-form')[0].reset();
                    formUrl = basePath + 'system/role/add';
                    if (data) {
                        formUrl = basePath + 'system/role/update';
                        form.val('role-form', data);
                    }
                    $('#role-form .close').click(function () {
                        layer.closeAll('page');
                    });
                }
            });
        };

        const del = function (id) {
            layer.confirm('确定要删除吗？', function () {
                layer.load(2);
                $.post(basePath + 'system/role/delete', {
                    roleId: id
                }, function (data) {
                    layer.closeAll('loading');
                    if (data.success) {
                        layer.msg(data.msg, {icon: 1});
                        table.reload('role-table', {});
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                });
            });
        };

        // 权限管理
        const auth = function (roleId) {
            layer.open({
                type: 1,
                title: '权限管理',
                area: ['450px', '450px'],
                offset: '120px',
                content: '<ul id="treeAuth" class="ztree" style="padding: 25px 0px 20px 60px;"></ul>',
                btn: ['保存', '关闭'],
                btnAlign: 'c',
                success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css('overflow-y', 'auto');
                    layer.load(2);
                    const setting = {
                        check: {enable: true},
                        data: {
                            simpleData: {enable: true}
                        }
                    };
                    $.get(basePath + 'system/role/authTree', {
                        roleId: roleId
                    }, function (data) {
                        $.fn.zTree.init($('#treeAuth'), setting, data);
                        layer.closeAll('loading');
                    }, 'json');
                },
                yes: function (index) {
                    layer.load(1);
                    const treeObj = $.fn.zTree.getZTreeObj('treeAuth');
                    const nodes = treeObj.getCheckedNodes(true);
                    const ids = [];
                    for (let i = 0; i < nodes.length; i++) {
                        ids[i] = nodes[i].id;
                    }
                    $.post(basePath + 'system/role/updateRoleAuth', {
                        roleId: roleId,
                        authIds: JSON.stringify(ids)
                    }, function (data) {
                        layer.closeAll('loading');
                        if (data.success) {
                            layer.msg(data.msg, {icon: 1});
                            layer.close(index);
                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }
                    }, 'json');
                }
            });
        };


        // 搜索按钮点击事件
        $('#role-btn-search').click(function () {
            const searchValue = $('#role-edit-search').val();
            table.reload('role-table', {where: {searchValue: searchValue}});
        });
    });

</script>